package logic

import (
	"context"
	"fmt"
	"time"

	"oil-station-backend/internal/svc"
	"oil-station-backend/internal/types"
)

type AdminLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAdminLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminLogic {
	return &AdminLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminLogic) UpdateFuelPrice(req *types.UpdateFuelPriceReq) (*types.FuelType, error) {
	fuelType, err := l.svcCtx.FuelTypeModel.UpdatePrice(req.Id, req.Price)
	if err != nil {
		return nil, err
	}

	return &types.FuelType{
		Id:    fuelType.Id,
		Type:  fuelType.Type,
		Name:  fuelType.Name,
		Price: fuelType.Price,
	}, nil
}

func (l *AdminLogic) GetInventory() ([]types.Inventory, error) {
	inventories, err := l.svcCtx.InventoryModel.FindAll()
	if err != nil {
		return nil, err
	}

	var result []types.Inventory
	for _, inv := range inventories {
		result = append(result, types.Inventory{
			Id:       inv.Id,
			FuelType: inv.FuelType,
			Stock:    inv.Stock,
			MinStock: inv.MinStock,
			MaxStock: inv.MaxStock,
		})
	}

	return result, nil
}

func (l *AdminLogic) UpdateInventory(req *types.UpdateInventoryReq) (*types.Inventory, error) {
	inventory, err := l.svcCtx.InventoryModel.UpdateStock(req.Id, req.Stock)
	if err != nil {
		return nil, err
	}

	return &types.Inventory{
		Id:       inventory.Id,
		FuelType: inventory.FuelType,
		Stock:    inventory.Stock,
		MinStock: inventory.MinStock,
		MaxStock: inventory.MaxStock,
	}, nil
}

func (l *AdminLogic) GetSalesReport(req *types.ReportReq) ([]types.SalesReport, error) {
	// 解析日期
	startDate, err := time.Parse("2006-01-02", req.StartDate)
	if err != nil {
		return nil, fmt.Errorf("开始日期格式错误: %v", err)
	}
	
	endDate, err := time.Parse("2006-01-02", req.EndDate)
	if err != nil {
		return nil, fmt.Errorf("结束日期格式错误: %v", err)
	}

	// 查询销售数据
	query := `
		SELECT 
			DATE(create_time) as date,
			COUNT(*) as total_orders,
			SUM(COALESCE(actual_amount, prepaid_amount)) as total_amount,
			SUM(COALESCE(actual_volume, volume)) as total_volume,
			fuel_type
		FROM orders 
		WHERE DATE(create_time) BETWEEN ? AND ? 
		GROUP BY DATE(create_time), fuel_type
		ORDER BY date DESC, fuel_type
	`

	rows, err := l.svcCtx.DB.Query(query, startDate.Format("2006-01-02"), endDate.Format("2006-01-02"))
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	// 用于聚合每日数据
	dailyData := make(map[string]*types.SalesReport)

	for rows.Next() {
		var date, fuelType string
		var orders int64
		var amount, volume float64

		err := rows.Scan(&date, &orders, &amount, &volume, &fuelType)
		if err != nil {
			return nil, err
		}

		// 如果该日期还没有记录，创建新记录
		if _, exists := dailyData[date]; !exists {
			dailyData[date] = &types.SalesReport{
				Date:         date,
				TotalOrders:  0,
				TotalAmount:  0,
				TotalVolume:  0,
				FuelTypeData: make([]struct {
					FuelType string  `json:"fuelType"`
					Orders   int64   `json:"orders"`
					Amount   float64 `json:"amount"`
					Volume   float64 `json:"volume"`
				}, 0),
			}
		}

		// 累加总数据
		dailyData[date].TotalOrders += orders
		dailyData[date].TotalAmount += amount
		dailyData[date].TotalVolume += volume

		// 添加油品类型数据
		dailyData[date].FuelTypeData = append(dailyData[date].FuelTypeData, struct {
			FuelType string  `json:"fuelType"`
			Orders   int64   `json:"orders"`
			Amount   float64 `json:"amount"`
			Volume   float64 `json:"volume"`
		}{
			FuelType: fuelType,
			Orders:   orders,
			Amount:   amount,
			Volume:   volume,
		})
	}

	// 转换为切片
	var result []types.SalesReport
	for _, report := range dailyData {
		result = append(result, *report)
	}

	return result, nil
}